package cn.tedu.smartos.health.service.impl;

//import cn.tedu.smartos.base.response.ServiceCode;
//import cn.tedu.smartos.base.response.ServiceException;
import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.health.mapper.HealthAlertMapper;
import cn.tedu.smartos.health.pojo.dto.HealthAlertParam;
import cn.tedu.smartos.health.pojo.entity.HealthAlertRecord;
import cn.tedu.smartos.health.pojo.vo.HealthAlertVO;
import cn.tedu.smartos.health.service.HealthAlertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class HealthAlertServiceImpl implements HealthAlertService {
    @Autowired
    private HealthAlertMapper healthAlertMapper;

    @Override
    public Long createAlert(HealthAlertParam alertParam) {
        log.info("创建健康预警，老人ID：{}", alertParam.getElderlyUserId());

        HealthAlertRecord alertRecord = new HealthAlertRecord();
        BeanUtils.copyProperties(alertParam, alertRecord);
        alertRecord.setAlertTime(new Date());
        alertRecord.setHandleStatus(0); // 默认未处理

        int rows = healthAlertMapper.insertAlert(alertRecord);
        if (rows != 1) {
            throw new ServiceException(StatusCode.FAILED, "创建健康预警失败");
        }

        return alertRecord.getAlertId();
    }

    @Override
    public List<HealthAlertVO> listAlertsByFamilyUserId(Long familyUserId) {
        log.info("获取家属用户ID：{}的所有预警通知", familyUserId);
        return healthAlertMapper.selectAlertsByFamilyUserId(familyUserId);
    }

    @Override
    public List<HealthAlertVO> listUnhandledAlertsByFamilyUserId(Long familyUserId) {
        log.info("获取家属用户ID：{}的未处理预警通知", familyUserId);
        return healthAlertMapper.selectUnhandledAlertsByFamilyUserId(familyUserId);
    }

    @Override
    public HealthAlertVO getAlertDetail(Long alertId) {
        log.info("获取预警ID：{}的详情", alertId);
        HealthAlertVO alertVO = healthAlertMapper.selectAlertById(alertId);
        if (alertVO == null) {
            throw new ServiceException(StatusCode.FAILED, "未找到该预警记录");
        }
        return alertVO;
    }

    @Override
    public boolean handleAlert(Long alertId, Long handleUserId, String handleComment) {
        log.info("处理预警ID：{}，处理人ID：{}", alertId, handleUserId);

        HealthAlertVO alertVO = healthAlertMapper.selectAlertById(alertId);
        if (alertVO == null) {
            throw new ServiceException(StatusCode.FAILED, "未找到该预警记录");
        }

        if (alertVO.getHandleStatus() == 1) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "该预警已处理");
        }

        int rows = healthAlertMapper.updateAlertStatus(alertId, 1, handleUserId, handleComment);
        return rows == 1;
    }
}